package com.easy.easy.Controller;

import com.easy.easy.Service.IUserService;
import com.easy.easy.Service.impl.UserService;
import com.easy.easy.bean.Category;
import com.easy.easy.bean.User;
import com.easy.easy.dao.UserDao;
import com.easy.easy.util.LayData;
import com.easy.easy.util.Page;
import com.easy.easy.util.SYS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    IUserService userService;

    @RequestMapping("list")
    @ResponseBody
    public LayData getlist(Page page,String text){
        List<User> list = userService.getlist(page,text);
        int count = userService.getCount(text);
        return new LayData(count,list);
    }

    @RequestMapping("delete")
    @ResponseBody
    public int delete(int id) {
        return userService.delete(id);
    }

    @RequestMapping("add")
    @ResponseBody
    public int add(User user) {
        return userService.add(user);
    }

    @RequestMapping("edit")
    @ResponseBody
    public int edit(User user) {
        return userService.edit(user);
    }

    @RequestMapping("current")
    @ResponseBody
    public User current(HttpSession session) {
        // 从 session 中获取当前登录的用户信息，使用 SYS.SHOPPING_LOGIN_USER 作为键
        User currentUser = (User) session.getAttribute(SYS.SHOPPING_LOGIN_USER);
        return currentUser;
    }
    @RequestMapping("getuserbyusername")
    @ResponseBody
    public LayData getUserByUsername(User user) {
        User userData=userService.getUser(user);
        return LayData.success(userData);
    }

    @RequestMapping("register")
    @ResponseBody
    public LayData register(User user, String confirmPassword) {
        // 检查 user 对象是否为空
        if (user == null) {
            return LayData.success(400, "用户信息不能为空");
        }

        // 检查用户名和密码格式是否正确
        boolean check = SYS.check("^\\w{6,16}$", user.getUsername(), user.getPassword());
        if (check) {
            return LayData.success(400, "输入格式不正确");
        }

        // 检查确认密码是否为空或与密码不一致
        if (confirmPassword == null || !confirmPassword.equals(user.getPassword())) {
            return LayData.success(400, "密码不一致");
        }

        // 检查用户名是否已存在
        User userData = userService.getUser(user);
        if (userData != null) {
            return LayData.success(400, "账号已经存在");
        }

        // 添加用户
        int count = userService.add(user);

        return LayData.success(userData);
    }

}
